#include <iostream>
#include <csignal>

#include "sources/fsm/fruit.hpp"
#include "sources/mech/mechanic.hpp"
#include "sources/timer/timer.hpp"
#include "sources/ui/ui.hpp"
#include "sources/log/logger.hpp"

//Running State
bool running = false;

void stop_me(int);

int main() {
    //Enter Running State
    running = true;

    signal(SIGTERM, stop_me);   //发送给程序的终止请求
    signal(SIGINT, stop_me);    //外部中断，通常为用户所起始

    std::cout << "Start..." << std::endl;

    //Start all thread.System will start working
    Logger::start_logger_thread("/intelli/logger/log.txt");
    OkTimer::start_timer_daemon();
    Mechanic::start_mechanical_thread();
    FruitFSM::start_sorting_kernel_thread();
    UIInteractive::start_ui_interactive_thread();
    std::cout << "Started" << std::endl;

    //Start wait thread
    std::cout << "Waiting the message..." << std::endl;
    UIInteractive::wait_ui_interactive_thread();
    FruitFSM::wait_sorting_kernel_thread();
    Mechanic::wait_mechanical_thread();
    OkTimer::wait_timer_daemon();
    Logger::wait_logger_thread();

    //Release resources,exit the program
    std::cout << "Finished" << std::endl;
    Logger::dispose();
    FruitFSM::dispose();
    UIInteractive::dispose();
    Mechanic::dispose();
    OkTimer::dispose();

    return 0;
}

//Stop all thread
void stop_me(int) {
    running = false;
    std::cout << "Stopping thread...." << std::endl;
    UIInteractive::stop_ui_interactive_thread();
    FruitFSM::stop_sorting_kernel_thread();
    Mechanic::stop_mechanical_thread();
    OkTimer::stop_timer_daemon();
    Logger::stop_logger_thread();
}
